var TailsParser = {

  parse: function(node, handler) {
    var objectsFoundCount = 0;
  
    var found = node.evaluate(this._scanQuery(),
        node, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);

    // ensure nodes are not just substring matches
    for (var i=0; i<found.snapshotLength; i++) {
      var node = found.snapshotItem(i);
      var formats = this._getFormatsForNode(node);
      for (var j=0; j<formats.length; j++) {
        objectsFoundCount++;
        if (handler) handler(formats[j],node);
      }
    }
    return objectsFoundCount;
  },


  _getFormatsForNode: function(node) {
    var r = [];
    var formats = TailsConfig.formats;
    for (var i=0; i<formats.length; i++) {
      if (node.getAttribute("class").match(formats[i].topNodePattern)) {
        r.push(formats[i]);
      }
    }
    return r;
  },

  // Generate the query for doing a preliminary scan
  _scanQuery: function() {
    var formats = TailsConfig.formats;
    var query = "";
    for (var i=0; i<formats.length; i++) {
      if (i != 0) query += " or ";
      query += "contains(@class, '" + formats[i].topNodeClass + "')";
    }
    return "//*[" + query + "]";
  }
};


